% 数据分析部分课设程序
% 对应题目编号都标记了，这里没有的题目说明可以可以用老师给的程序写。
%% 1.1
% 参数取值
clear, clc
mu = [0,0];
sigma = {[1 0; 0 1], [0.2 0; 0 0.2], [4 0; 0 4], [0.2 0; 0 4],... 
    [4 0; 0 0.2], [1 0.5; 0.5 1], [0.3, 0.5; 0.5, 4], [4, 0.5; 0.5, 0.3]}

for i = 1:length(sigma)
    figure(i)
    R = mvnrnd(mu,sigma{i},500);
    scatter(R(:,1), R(:,2), "filled")
    grid on
    saveas(i, ['ks_pic/',num2str(i),'.png'])
    
end

%% 1.2
clear, clc
% data = xlsread("data_1.xls");
data = readtable("data_1.xls");
size(data)
data(841,:) = [];
size(data)

name = data.Properties.VariableNames;
x = data.ID;
y = data.Variables;
k = 1;
for i = 2:length(name)
    for j = i+1:length(name)
       figure(k)
       scatter(y(:,i),y(:,j),20,'blue',"filled")
       xlabel(name{i})
       ylabel(name{j})
       saveas(k, ['ks_pic/','Second_',num2str(k),'.png'])
       
       k = k+1;
    end
end
figure
boxplot(y(:,2:end))
saveas(gca, ['ks_pic/','Second_b','.png'])
%
[R,P,RL,RU] = corrcoef(y(:,2:end))

%% 1.3
clear, clc
data = [13.54,14.36,87.46,566.3,0.09779;
        13.08,15.71,85.63,520,0.1075;
        9.504,12.44,60.34,273.9,0.1024;
        17.99,10.38,122.8,1001,0.1184;
        20.57,17.77,132.9,1326,0.08474;
        19.69,21.25,130,1203,0.1096;
        11.42,20.38,77.58,386.1,0.1425;
        20.29,14.34,135.1,1297,0.1003];
sample = [16.6,28.08,108.3,858.1,0.08455;
            20.6,29.33,140.1,1265,0.1178;
            7.76,24.54,47.92,181,0.05263];
%首先计算两类样本均值点
mu_1 = mean(data(1:3,:),1)
mu_2 = mean(data(4:end,:),1)
ans = []; %存放答案

%如果协方差相等
for i = 1:size(sample,1)
    x = sample(i,:);
    dis1 = - norm(x - mu_1) + log(3/8);
    dis2 = - norm(x - mu_2) + log(5/8);
    if dis1 < dis2
        ans = [ans,2];
    elseif dis2 < dis1
        ans = [ans,1];
    else
        ans = [ans,0] % 两类都行
    end
end

disp(ans)
                    
%如果协方差不相同

cov1 = cov(data(1:3,:));  %良性样本
cov2 = cov(data(4:end,:));
ans = [];
for i = 1:size(sample,1)
    x = sample(i,:);
    dis1 = - (x - mu_1) * cov1 * (x - mu_1)' + log(3/8);
    dis2 = - (x - mu_2) * cov1 * (x - mu_2)' + log(5/8);
    if dis1 < dis2
        ans = [ans,2];
    elseif dis2 < dis1
        ans = [ans,1];
    else
        ans = [ans,0] % 两类都行
    end
end
disp(ans)

%% 2.1
clear, clc
DATA = readtable("data21.xls");
data = xlsread("data21.xls",'B4:I34');
place = DATA(:,1);
place = table2array(place);
[coeff,score,latent,tsquared,explained] = pca(data)
y1 = data * coeff(:,1);
y2 = data * coeff(:,2);
figure
scatter(y1,y2,"filled");
xlabel('第一主成分')
ylabel('第二主成分')
for i = 1:length(y1)
    text(y1(i),y2(i),place(i))
end
saveas(gca,['ks_pic/','2.1_3.png'])

%% 3.1_1
clear,clc,close all
data = readtable("data31.xls");
class = table2array( data(:,2) );
%选取变量维度
X = table2array( data(:,3:end) ); %四个变量全选
X = X(:,[2,4]);%选X_2,X_4

%1. 随机选取聚类中心点
class_num = 3;
[n_sample, dim] = size(X);
label = zeros(1,n_sample); % 类别标签初始化
ind = randperm(n_sample); % 随机排列后的index
fenge = floor(n_sample / class_num);
center = zeros(class_num, dim);
for i = 1 : class_num
    if i < class_num
        center(i,:) = mean(X(ind( (i-1)*fenge + 1 : i*fenge),:), 1);
        label(ind( (i-1)*fenge + 1 : i*fenge)) = i;
    else
        center(i,:) = mean(X(ind( (i-1)*fenge + 1 : end),:), 1);
        label(ind( (i-1)*fenge + 1 : end)) = i;
    end
end
figure
scatter(X(:,1), X(:,end),10,label,"filled")
% scatter3(X(:,1), X(:,2), X(:,end),10,label,"filled")
% saveas(gca,'ks_pic/Third3.1_(1)_1.png')
print(gcf, '-dpng', '-r300', 'ks_pic/Third3.1_(1)_1.png')         %即可得到对应格式和期望dpi的图像
step = 10; %聚类计算10次
k=2;
accracy = 0; %聚类准确率：也就是1-差异率(差异率：新分类与旧分类的差异)
while accracy < 0.95
    old_label = label;
    for i = 1:n_sample
        D = zeros(1, class_num); %每个点到聚类中心的距离
        for j = 1:class_num
            D(j) = pdist([X(i,:); center(j,:)]);
        end
        [~,ind] = min(D); %找到改点距离哪个点距离最近，找到其索引
        label(i) = ind;
    end
    center = comput_center(X, label) %更新聚类中心
    figure
    scatter(X(:,1), X(:,end),10,label,"filled")
%     scatter3(X(:,1), X(:,2), X(:,end),10,label,"filled")
    step = step -1;
%     saveas(gca,['ks_pic/Third3.1_(1)_', num2str(k), '.png'])
    print(gcf, '-dpng', '-r300', ['ks_pic/Third3.1_(1)_', num2str(k), '.png'])
    accracy = sum(old_label==label)/length(label);
    k = k+1;
end


%% 3.1_2
clear,clc,close all
data = readtable("data31.xls");
class = table2array( data(:,2) );
%选取变量维度
X = table2array( data(:,3:end) ); %四个变量全选
X = X(:,[1,2,3]);%选X1,X2,X3
%1. 随机选取聚类中心点
class_num = 3;
[n_sample, dim] = size(X);
label = zeros(1,n_sample); % 类别标签初始化
ind = randperm(n_sample); % 随机排列后的index
fenge = floor(n_sample / class_num);
center = zeros(class_num, dim);
for i = 1 : class_num
    if i < class_num
        center(i,:) = mean(X(ind( (i-1)*fenge + 1 : i*fenge),:), 1);
        label(ind( (i-1)*fenge + 1 : i*fenge)) = i;
    else
        center(i,:) = mean(X(ind( (i-1)*fenge + 1 : end),:), 1);
        label(ind( (i-1)*fenge + 1 : end)) = i;
    end
end
figure
% scatter(X(:,1), X(:,end),10,label,"filled")
scatter3(X(:,1), X(:,2), X(:,end),10,label,"filled")
% saveas(gca,'ks_pic/Third3.1_(1)_1.png')
print(gcf, '-dpng', '-r400', 'ks_pic/Third3.1_(2)_1.png')         %即可得到对应格式和期望dpi的图像
step = 10; %聚类计算10次
k=2;
accracy = 0; %聚类准确率：也就是1-差异率(差异率：新分类与旧分类的差异)
while accracy < 0.95
    old_label = label;
    for i = 1:n_sample
        D = zeros(1, class_num); %每个点到聚类中心的距离
        for j = 1:class_num
            D(j) = pdist([X(i,:); center(j,:)]);
        end
        [~,ind] = min(D); %找到改点距离哪个点距离最近，找到其索引
        label(i) = ind;
    end
    center = comput_center(X, label) %更新聚类中心
    figure
%     scatter(X(:,1), X(:,end),10,label,"filled")
    scatter3(X(:,1), X(:,2), X(:,end),10,label,"filled")
    step = step -1;
%     saveas(gca,['ks_pic/Third3.1_(1)_', num2str(k), '.png'])
    print(gcf, '-dpng', '-r400', ['ks_pic/Third3.1_(2)_', num2str(k), '.png'])
    accracy = sum(old_label==label)/length(label);
    k = k+1;
end

%% 3.1_3
clear,clc,close all
data = readtable("data31.xls");
class = table2array( data(:,2) );
%选取变量维度
X = table2array( data(:,3:end) ); %四个变量全选
% X = X(:,[1,2,3]);%选X1,X2,X3
%1. 随机选取聚类中心点
class_num = 3;
[n_sample, dim] = size(X);
label = zeros(1,n_sample); % 类别标签初始化
ind = randperm(n_sample); % 随机排列后的index
fenge = floor(n_sample / class_num);
center = zeros(class_num, dim);
for i = 1 : class_num
    if i < class_num
        center(i,:) = mean(X(ind( (i-1)*fenge + 1 : i*fenge),:), 1);
        label(ind( (i-1)*fenge + 1 : i*fenge)) = i;
    else
        center(i,:) = mean(X(ind( (i-1)*fenge + 1 : end),:), 1);
        label(ind( (i-1)*fenge + 1 : end)) = i;
    end
end
figure
% scatter(X(:,1), X(:,end),10,label,"filled")
scatter3(X(:,1), X(:,2), X(:,end),10,label,"filled")
% saveas(gca,'ks_pic/Third3.1_(1)_1.png')
print(gcf, '-dpng', '-r400', 'ks_pic/Third3.1_(3)_1.png')         %即可得到对应格式和期望dpi的图像
step = 10; %聚类计算10次
k=2;
accracy = 0; %聚类准确率：也就是1-差异率(差异率：新分类与旧分类的差异)
while accracy < 0.95
    old_label = label;
    for i = 1:n_sample
        D = zeros(1, class_num); %每个点到聚类中心的距离
        for j = 1:class_num
            D(j) = pdist([X(i,:); center(j,:)]);
        end
        [~,ind] = min(D); %找到改点距离哪个点距离最近，找到其索引
        label(i) = ind;
    end
    center = comput_center(X, label) %更新聚类中心
    figure
%     scatter(X(:,1), X(:,end),10,label,"filled")
    scatter3(X(:,1), X(:,2), X(:,end),10,label,"filled")
    step = step -1;
%     saveas(gca,['ks_pic/Third3.1_(1)_', num2str(k), '.png'])
    print(gcf, '-dpng', '-r400', ['ks_pic/Third3.1_(3)_', num2str(k), '.png'])
    accracy = sum(old_label==label)/length(label);
    k = k+1;
end
